<template>
  <div class="reports-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>报表与统计</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 统计信息 -->
        <el-tab-pane label="统计信息" name="statistics">
          <div class="statistics-section">
            <h3>图书统计</h3>
            <el-row :gutter="20" v-loading="bookStatsLoading">
              <el-col :span="6">
                <el-statistic title="图书总数" :value="bookStatistics.totalBooks || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="总库存" :value="bookStatistics.totalStock || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="推荐图书" :value="bookStatistics.recommendedBooks || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="分类数量" :value="bookStatistics.categoryCount || 0" />
              </el-col>
            </el-row>

            <h3 style="margin-top: 30px">借阅统计</h3>
            <el-row :gutter="20" v-loading="borrowStatsLoading">
              <el-col :span="6">
                <el-statistic title="总借阅数" :value="borrowStatistics.totalBorrows || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="当前借阅" :value="borrowStatistics.currentBorrows || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="已归还" :value="borrowStatistics.returnedBorrows || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="待确认归还" :value="borrowStatistics.pendingReturns || 0" />
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 报表导出 -->
        <el-tab-pane label="报表导出" name="exports">
          <div class="export-section">
            <el-card shadow="hover" class="export-card">
              <template #header>
                <div class="export-header">
                  <el-icon><Document /></el-icon>
                  <span>图书列表</span>
                </div>
              </template>
              <p>导出所有图书信息到CSV文件</p>
              <el-button type="primary" @click="handleExportBooks" :loading="exportingBooks">
                <el-icon><Download /></el-icon>
                导出图书列表
              </el-button>
            </el-card>

            <el-card shadow="hover" class="export-card">
              <template #header>
                <div class="export-header">
                  <el-icon><List /></el-icon>
                  <span>借阅记录</span>
                </div>
              </template>
              <p>导出所有借阅记录到CSV文件</p>
              <el-button type="primary" @click="handleExportBorrowRecords" :loading="exportingBorrow">
                <el-icon><Download /></el-icon>
                导出借阅记录
              </el-button>
            </el-card>

            <el-card shadow="hover" class="export-card">
              <template #header>
                <div class="export-header">
                  <el-icon><User /></el-icon>
                  <span>用户列表</span>
                </div>
              </template>
              <p>导出所有用户信息到CSV文件</p>
              <el-button type="primary" @click="handleExportUsers" :loading="exportingUsers">
                <el-icon><Download /></el-icon>
                导出用户列表
              </el-button>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Download, List, User } from '@element-plus/icons-vue'
import { bookAPI, borrowAPI, reportAPI } from '../services/api'

const activeTab = ref('statistics')
const bookStatistics = ref({})
const borrowStatistics = ref({})
const bookStatsLoading = ref(false)
const borrowStatsLoading = ref(false)
const exportingBooks = ref(false)
const exportingBorrow = ref(false)
const exportingUsers = ref(false)

const fetchBookStatistics = async () => {
  bookStatsLoading.value = true
  try {
    const response = await bookAPI.getStatistics()
    bookStatistics.value = response
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取图书统计失败')
  } finally {
    bookStatsLoading.value = false
  }
}

const fetchBorrowStatistics = async () => {
  borrowStatsLoading.value = true
  try {
    const response = await borrowAPI.getBorrowStatistics()
    borrowStatistics.value = response
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取借阅统计失败')
  } finally {
    borrowStatsLoading.value = false
  }
}

const handleExportBooks = async () => {
  exportingBooks.value = true
  try {
    const response = await reportAPI.exportBooks()
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'books.csv')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '导出失败')
  } finally {
    exportingBooks.value = false
  }
}

const handleExportBorrowRecords = async () => {
  exportingBorrow.value = true
  try {
    const response = await reportAPI.exportBorrowRecords()
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'borrow_records.csv')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '导出失败')
  } finally {
    exportingBorrow.value = false
  }
}

const handleExportUsers = async () => {
  exportingUsers.value = true
  try {
    const response = await reportAPI.exportUsers()
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'users.csv')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '导出失败')
  } finally {
    exportingUsers.value = false
  }
}

onMounted(() => {
  fetchBookStatistics()
  fetchBorrowStatistics()
})
</script>

<style scoped>
.reports-container {
  height: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
}

.statistics-section {
  padding: 20px 0;
}

.statistics-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.export-section {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.export-card {
  transition: all 0.3s ease;
}

.export-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.export-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.export-card p {
  color: #606266;
  margin: 12px 0;
  font-size: 14px;
}

@media (max-width: 768px) {
  .export-section {
    grid-template-columns: 1fr;
  }
}
</style>

